//
//  MYGHealthManagementViewController.swift
//  MYGrow
//
//  Created by 林矗 on 2024/3/9.
//

import UIKit
import MobileCoreServices

class MYGHealthManagementViewController: MYGBaseController {
    // MARK: - Property
    var sections: [MYGHealthManagementSectionModel] = []
    var type: MYGHealthManagementType = .statistics
    var name: String = ""
    var headUrl: String = ""
    var patientId = 0
    override var navigationBackgroundColor: UIColor {
        .clear
    }
    
    override var navigationShadowColor: UIColor {
        .clear
    }
    
    // MARK: - life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
        configItem()
        MYGHealthManager.shareManager.patientId = String(patientId)
        MYGHealthManager.shareManager.userInfo = nil
        switch type {
        case .statistics:
            loadHealthData()
        case .habit:
            loadFoodAndSportData()
            loadUserData()
        case .history:
            loadUserData()
        case .report:
            loadReportData()
        }
    }
    
    // MARK: - UI
    private func configUI() {
        view.backgroundColor = .white
        title = "健康档案"
        
        view.addSubviews([
            headView,
            cardView
        ])
        
        cardView.addSubviews([
            tableView
        ])
        
        headView.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
        }
        
        cardView.snp.makeConstraints { make in
            make.top.equalTo(headView.snp.bottom).offset(-35)
            make.left.right.bottom.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
    }
    
    private func configItem() {
        let statisticsSecion = MYGHealthManagementSectionModel(type: .statistics, items: [
            MYGHealthManagementStatisticsModel(statisticsType: .pressure, value1: "--mmHg", value2: "--mmHg", target: self, selector: #selector(loadPressureData)),
            MYGHealthManagementStatisticsModel(statisticsType: .sugar, value1: "--mmol/L", value2: "--mmol/L", target: self, selector: #selector(loadSugarData)),
            MYGHealthManagementStatisticsModel(statisticsType: .heart, value1: "--次/分", target: self, selector: #selector(loadHeartRateData)),
            MYGHealthManagementStatisticsModel(statisticsType: .bmi, value1: "--", target: self, selector: #selector(loadBMIData)),
        ])
        
        let habitSecion = MYGHealthManagementSectionModel(type: .habit, items: [
            MYGHealthManagementNormalTextModel(type: .smoke, delegate: self),
            MYGHealthManagementNormalTextModel(type: .drink, delegate: self),
            MYGHealthManagementNormalTextModel(type: .sleep, delegate: self),
            MYGHealthManagementFoodModel(todayIn: "0kcal", lastDayCompary: "0kcal", carbon: "0g", fat: "0g", protein: "0g", delegate: self),
            MYGHealthManagementSportModel(today: "0分钟", lastDayCompare: "0分钟", time: "0分钟", delegate: self)
        ])
        
        let historySection = MYGHealthManagementSectionModel(type: .history, items: [
            MYGHealthManagementNormalTextModel(type: .touch, delegate: self),
            MYGHealthManagementNormalTextModel(type: .ill, delegate: self),
            MYGHealthManagementNormalTextModel(type: .family, delegate: self),
            MYGHealthManagementNormalTextModel(type: .op, delegate: self),
            MYGHealthManagementNormalTextModel(type: .medical, delegate: self),
            MYGHealthManagementNormalTextModel(type: .allergy, delegate: self),
        ])
        
        let reportSection = MYGHealthManagementSectionModel(type: .report, items: [])
        

        self.sections = [statisticsSecion, habitSecion, historySection, reportSection]
        
        self.tableView.reloadData()
    }
    
    
    private func reloadNormalTextItem() {
        
    }
    
    @objc func loadData() {
        loadHealthData()
        loadFoodAndSportData()
        loadReportData()
    }
    
    @objc func loadHealthData() {
        loadPressureData()
        loadSugarData()
        loadHeartRateData()
        loadBMIData()
    }
    
    @objc func loadUserData() {
        MYGLoading.show(view)
        MYGHealthManager.shareManager.loadUser {
            MYGLoading.hide(self.view)
            self.tableView.reloadData()
        }
    }
    
    @objc func loadFoodAndSportData() {
        MYGLoading.show(view)
        MYGMedicalToolsCalorieManager.shareManager.loadTodayFoodAndSportData { food, sport in
            let foodCompare = ((food?.kilocalories_all ?? "0").int ?? 0) - ((food?.yesterday_kilocalories_all ?? "0").int ?? 0)
            let sportCompare = ((sport?.motions_all ?? "0").int ?? 0) - ((sport?.yesterday_motions_all ?? "0").int ?? 0)

            self.updateModel(at: IndexPath(item: 3, section: MYGHealthManagementType.habit.index), with:MYGHealthManagementFoodModel(todayIn: "\(food?.kilocalories_all ?? "0")kcal", lastDayCompary: "\(foodCompare)kcal", carbon: "\(food?.carbons_all ?? "0")g", fat: "\(food?.fats_all ?? "0")g", protein: "\(food?.proteins_all ?? "0")g", delegate: self))
            
            
            self.updateModel(at: IndexPath(item: 4, section: MYGHealthManagementType.habit.index), with: MYGHealthManagementSportModel(today: "\(sport?.motions_all ?? "0")分钟", lastDayCompare: "\(sportCompare)分钟", time: "\(sport?.motions_all ?? "0")分钟", delegate: self))
            MYGLoading.hide(self.view)
        }
    }
    
    @objc func loadPressureData() {
        MYGHealthManager.shareManager.getPressureData { _, todayModel in
            if let todayModel = todayModel  {
                self.updateModel(at:IndexPath(item: 0, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .pressure, value1: "\(todayModel.systolic_pressure)mmHg", value2: "\(todayModel.diastolic_pressure)mmHg", target: self, selector: #selector(self.loadPressureData)))
            } else {
                self.updateModel(at:IndexPath(item: 0, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .pressure, value1: "--mmHg", value2: "--mmHg", target: self, selector: #selector(self.loadPressureData)))
            }
        }
    }
    
    @objc func loadSugarData() {
        MYGHealthManager.shareManager.getSugarData { _, todayModel in
            if let todayModel = todayModel  {
                self.updateModel(at:IndexPath(item: 1, section: MYGHealthManagementType.statistics.index) , with: MYGHealthManagementStatisticsModel(statisticsType: .sugar, value1: "\(todayModel.blood_glucose_level)mmol/L", value2: "\(todayModel.blood_glucose_level)mmol/L", target: self, selector: #selector(self.loadSugarData)))
            } else {
                self.updateModel(at:IndexPath(item: 1, section: MYGHealthManagementType.statistics.index) , with: MYGHealthManagementStatisticsModel(statisticsType: .sugar, value1: "--mmol/L", value2: "--mmol/L", target: self, selector: #selector(self.loadSugarData)))
            }
        }
    }
    
    @objc func loadHeartRateData() {
        MYGHealthManager.shareManager.getHeartRateData { _, todayModel in
            if let todayModel = todayModel  {
                self.updateModel(at:IndexPath(item: 2, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .heart, value1: "\(todayModel.heart_rate_value)次/分", target: self, selector: #selector(self.loadHeartRateData)))
            } else {
                self.updateModel(at:IndexPath(item: 2, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .heart, value1: "--次/分", target: self, selector: #selector(self.loadHeartRateData)))
            }
        }
    }
    
    @objc func loadBMIData() {
        MYGHealthManager.shareManager.getBMIData { _, todayModel in
            if let todayModel = todayModel  {
                self.updateModel(at:IndexPath(item: 3, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .bmi, value1: "\(todayModel.bmi)", target: self, selector: #selector(self.loadBMIData)))
            } else {
                self.updateModel(at:IndexPath(item: 3, section: MYGHealthManagementType.statistics.index) , with:MYGHealthManagementStatisticsModel(statisticsType: .bmi, value1: "--", target: self, selector: #selector(self.loadBMIData)))
            }
        }
    }
    
    @objc func loadReportData() {
        MYGNetwork<MYGHealthApi, MYGPageModel<MYGHealthManagementReportDataModel>>.request(target: .reportList(patientId: String(patientId))) { result in
            let models = result.list.map { model in
                MYGHealthManagementReportModel(headUrl: self.headUrl, name: self.name , sex: 1, time: model.time, location: model.name, num: "编号：\(model.number)", url: model.file_url)
            }
            
            self.sections[MYGHealthManagementType.report.index] =  MYGHealthManagementSectionModel(type: .report, items: models)
            self.tableView.reloadData()
        } failed: { _, error in
        
        }
    }
    
    
    func updateModel(at indexPath: IndexPath, with model: MYGHealthManagementRowModel) {
        sections[indexPath.section].items[indexPath.row] = model
        tableView.reloadRows(at: [indexPath], with: .none)
    }
    
    // MARK: - lazy load
    private lazy var headView: MYGHealthManagementHeadView = {
        let view = MYGHealthManagementHeadView(frame: .zero)
        view.name = name
        view.headImageUrl = headUrl
        view.action = {
            self.goToInfoEvent()
        }
        return view
    }()
    
    private lazy var cardView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layerCornerRadius = 15
        return view
    }()
    
    private lazy var topTab: MYGHealthManagementTopTab = {
        let tab = MYGHealthManagementTopTab(frame: .zero)
        tab.itemDidSelectAction = {[weak self](index) in
            self?.tableView.scrollToRow(at: IndexPath(item: 0, section: index), at: .top, animated: true)
        }
        return tab
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.estimatedRowHeight = 120
        tableView.register(headerFooterViewClassWith: MYGHealthManagementSectionHeader.self)
        tableView.register(cellWithClass: MYGHealthManagementBaseCell.self)
        tableView.register(cellWithClass: MYGHealthManagementStatisticsCell.self)
        tableView.register(cellWithClass: MYGHealthManagementNormalTextCell.self)
        tableView.register(cellWithClass: MYGHealthManagementFoodCell.self)
        tableView.register(cellWithClass: MYGHealthManagementSportCell.self)
        tableView.register(cellWithClass: MYGHealthManagementReportCell.self)
        return tableView
    }()
}

extension MYGHealthManagementViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        sections[type.index].items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sectionModel = sections[type.index]
        switch sectionModel.items[indexPath.row].type {
        case .statistics:
            let cell = tableView.dequeueReusableCell(withClass: MYGHealthManagementStatisticsCell.self)
            cell.model = sectionModel.items[indexPath.row]
            return cell
        case .normal:
            let cell = tableView.dequeueReusableCell(withClass: MYGHealthManagementNormalTextCell.self)
            cell.model = sectionModel.items[indexPath.row]
            return cell
        case .food:
            let cell = tableView.dequeueReusableCell(withClass: MYGHealthManagementFoodCell.self)
            cell.model = sectionModel.items[indexPath.row]
            return cell
        case .sport:
            let cell = tableView.dequeueReusableCell(withClass: MYGHealthManagementSportCell.self)
            cell.model = sectionModel.items[indexPath.row]
            return cell
        case .report:
            let cell = tableView.dequeueReusableCell(withClass: MYGHealthManagementReportCell.self)
            cell.shareAction = { model in
                guard let model = model else { return }
                self.share(with: model)
            }
            
            cell.clickAction = { model in
                guard let model = model else { return }
                model.action?()
            }
            cell.model = sectionModel.items[indexPath.row]
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        sections[type.index].items[indexPath.row].action?()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withClass: MYGHealthManagementSectionHeader.self)
        header.title = sections[type.index].title
        header.addBtnisHidden = true
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if !(scrollView.isTracking || scrollView.isDecelerating) { return }
        let section = tableView.qmui_indexForVisibleSectionHeaders?.first
        guard let section = section else { return }
        topTab.selectedIndex = section.intValue
    }
}


extension MYGHealthManagementViewController {
    @objc private func goToInfoEvent() {
//        let vc = MYGBaseInfoViewController()
//        navigationController?.pushViewController(vc)
    }
    
    @objc private func share(with model: MYGHealthManagementReportModel) {
//        let view = MYGHealthManagementShareView()
//        let sheet = MYGBottomSheetView(with: view)
//        sheet.title = ""
//        sheet.show(animated: true)
//        view.action = {index in
//            sheet.hide(animated: true)
//            if index == 3 {
//                let vc = MYGSelectUserController()
//                UIViewController.currentViewController?.navigationController?.pushViewController(vc)
//            }
//        }
    }
}


extension MYGHealthManagementViewController: MYGHealthManagementRowModelDelegate {
    func valueChanged(model: MYGHealthManagementRowModel) {
       
    }
}
